package com.alibaba.dingtalk.openapi.newmessage.utils;/*/*/

import com.alibaba.dingtalk.openapi.exception.OApiException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Objects;


/**
 *
 * @author 魏荣杰
 * @date 2019/3/22 16:32
 * @since v1.0
 * @version v1.0
 */
public class HttpHelper {
    private static final Logger LOG = LoggerFactory.getLogger(HttpHelper.class);

    public static JSONObject httpPost(String url, Object data) throws OApiException {
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = null;

        try {
            httpClient = HttpClients.createDefault();
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
            httpPost.setConfig(requestConfig);
            httpPost.addHeader("Content-Type", "application/json");
            StringEntity requestEntity = new StringEntity(JSON.toJSONString(data), "utf-8");
            httpPost.setEntity(requestEntity);
            response = httpClient.execute(httpPost, new BasicHttpContext());
            if (url.contains("/topapi/message/corpconversation/sendbytemplate")){
                LOG.warn("-------response:{},url:{}",JSON.toJSONString(response), url);
            }
            if (!Objects.equals(response.getStatusLine().getStatusCode(), 200)) {
                throw new OApiException(SystemErrorCodeEnum.API_ERROR_100063.getCode(), "com.alibaba.dingtalk.openapi.newmessage.utils.HttpHelper.httpPost Request:  " + url + I18nMessageUtil.getMessage(I18nStringConstant.REQUEST_NETWORK_ERROR));
            }

            HttpEntity entity = response.getEntity();
            if (!Objects.isNull(entity)) {
                String resultStr = EntityUtils.toString(entity, "utf-8");
                JSONObject result = JSON.parseObject(resultStr);
                return result;
            }

        } catch (ClientProtocolException e) {
            LOG.error("com.alibaba.dingtalk.openapi.newmessage.utils.HttpHelper.httpPost，msg= " + e.getMessage(), e);
        } catch (IOException e) {
            LOG.error("com.alibaba.dingtalk.openapi.newmessage.utils.HttpHelper.httpPost 请求链接失败，msg= " + e.getMessage(), e);
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    LOG.error("com.alibaba.dingtalk.openapi.newmessage.utils.HttpHelper.httpPost close httpClient fail， url=" + url + ", exception, msg=" + e.getMessage(), e);
                }
            }
            if (!Objects.isNull(response)) {
                try {
                    response.close();
                } catch (IOException e) {
                    LOG.error("com.alibaba.dingtalk.openapi.newmessage.utils.HttpHelper.httpPost 关闭链接失败，msg= " + e.getMessage(), e);
                }
            }
        }
        return null;
    }

    /**
     * Description: http异步请求（json格式，post）
     * @param url
     * @param data
     * @throws
     * @author 魏荣杰
     * @date 2021/1/7 09:49
     * @since
     */
    public static void httpAsyncPost(String url, Object data) {
        RequestConfig requestConfig = RequestConfig.custom().
                setSocketTimeout(5000).setConnectTimeout(5000).build();
        final CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig).build();


        StringEntity requestEntity = new StringEntity(JSON.toJSONString(data), ContentType.APPLICATION_JSON);

        final HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(requestEntity);
        httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");

        httpAsyncClient.start();
//        Future<HttpResponse> future;
        try {
//            future = httpAsyncClient.execute(httpPost, new FutureCallback<HttpResponse>() {
            httpAsyncClient.execute(httpPost, new FutureCallback<HttpResponse>() {
                @Override
                public void completed(HttpResponse httpResponse) {
                    try {
                        if (httpResponse.getStatusLine().getStatusCode() != 200) {
                            LOG.error("com.alibaba.dingtalk.openapi.newmessage.utils.HttpHelper#httpAsyncPost request url failed, http code=" + httpResponse.getStatusLine().getStatusCode() + ", url=" + url);
                        }
                        org.apache.http.HttpEntity entity = httpResponse.getEntity();
                        if (entity != null) {
                            String resultStr = EntityUtils.toString(entity, "utf-8");
                            LOG.info("com.alibaba.dingtalk.openapi.newmessage.utils.HttpHelper#httpAsyncPost resultStr = " + resultStr);
                        }
                    } catch (Exception e) {
                        LOG.error("com.alibaba.dingtalk.openapi.newmessage.utils.HttpHelper#httpAsyncPost request url=" + url + ", exception, msg=" + e.getMessage(), e);
                    } finally {
                        if (httpAsyncClient != null) {
                            try {
                                httpAsyncClient.close();
                            } catch (IOException e) {
                                LOG.error("com.alibaba.dingtalk.openapi.newmessage.utils.HttpHelper.httpAsyncPost POST execute httpAsyncClient close exception ", e);
                            }
                        }
                    }
                }

                @Override
                public void failed(Exception e) {
                    if (httpAsyncClient != null) {
                        try {
                            httpAsyncClient.close();
                        } catch (IOException ex) {
                            LOG.error("com.alibaba.dingtalk.openapi.newmessage.utils.HttpHelper.httpAsyncPost POST execute httpAsyncClient close exception ", ex);
                        }
                    }
                }

                @Override
                public void cancelled() {
                    if (httpAsyncClient != null) {
                        try {
                            httpAsyncClient.close();
                        } catch (IOException e) {
                            LOG.error("com.alibaba.dingtalk.openapi.newmessage.utils.HttpHelper#httpAsyncPost POST execute httpAsyncClient close exception ", e);
                        }
                    }
                }
            });
        } catch (Exception e) {
            LOG.error("com.alibaba.dingtalk.openapi.newmessage.utils.HttpHelper#httpAsyncPost fail request url=" + url + ", exception, msg=" + e.getMessage(), e);
        }

    }
}
